package com.tuxianchao.demo.springbootasync.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * created by
 *
 * @author tuxianchao
 * @date 2018/6/3 下午4:53
 */
@Configuration
public class ThreadPoolConfig {
    @Bean("taskExecutor")
    public Executor taskExcutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //核心线程数10
        executor.setCorePoolSize(10);
        //最大线程数20
        executor.setMaxPoolSize(20);
        //缓冲队列200
        executor.setQueueCapacity(200);
        //允许空闲时间
        executor.setKeepAliveSeconds(60);
        //线程池中name前缀
        executor.setThreadNamePrefix("taskExecutor-");
        //线程池对拒绝任务的处理策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());

        //设置线程池关闭的时候等待所有任务都完成再继续销毁其他的，例如依赖redis，这样异步任务的销毁就会先于Redis线程池的销毁
        executor.setWaitForTasksToCompleteOnShutdown(true);
        //设置线程池中任务的等待时间，如果超过这个时候还没有销毁就强制销毁，以确保应用最后能够被关闭，而不是阻塞住
        executor.setAwaitTerminationSeconds(60);
        return executor;
    }
}
